<template>
    <el-container>
        <el-aside width="200px">
            <el-container>
                <el-header>
                    <el-input
                        placeholder="输入关键字进行过滤"
                        v-model="state.groupFilterText"
                        clearable
                    ></el-input>
                </el-header>
                <el-main class="nopadding">
                    <el-tree
                        ref="groupRef"
                        class="menu"
                        node-key="id"
                        :data="state.group"
                        :current-node-key="''"
                        :highlight-current="true"
                        :expand-on-click-node="false"
                        :filter-node-method="groupFilterNode"
                        @node-click="groupClick"
                    ></el-tree>
                </el-main>
            </el-container>
        </el-aside>
        <el-container>
            <el-header>
                <div class="left-panel">
                    <el-button
                        type="primary"
                        icon="el-icon-plus"
                        @click="add"
                        v-auths-all="['settingAdminEdit']"
                    ></el-button>
                    <el-button
                        type="danger"
                        plain
                        icon="el-icon-delete"
                        :disabled="selection.length == 0"
                        class="right-btn"
                        v-auths-all="['settingAdminBatchDel']"
                        @click="batchDel"
                    ></el-button>
                </div>
                <div class="right-panel">
                    <div class="right-panel-search" style="width: 400px">
                        <el-input
                            v-model="state.search.name"
                            placeholder="id/登录账号/真实姓名/昵称/手机号/邮箱"
                            clearable
                        ></el-input>
                        <el-button
                            type="primary"
                            icon="el-icon-search"
                            @click="handleSearch"
                        ></el-button>
                    </div>
                </div>
            </el-header>
            <el-main class="nopadding">
                <kitegoTable
                    ref="kitegoTableRef"
                    :apiObj="state.apiObj"
                    @selection-change="selectionChange"
                    stripe
                    :columns="columns"
                >
                    <template #avatar="scope">
                        <el-avatar :src="scope.row.avatar" size="small"></el-avatar>
                    </template>
                    <template #status="scope">
                        <el-tag type="success" v-if="scope.row.status == 1">已启用</el-tag>
                        <el-tag type="danger" v-if="scope.row.status == 2">已禁用</el-tag>
                        <el-tag type="warning" v-if="scope.row.status == 3">待审核</el-tag>
                    </template>
                    <template #loginCount="scope">
                        <el-row>
                            <el-text size="small">总次数:{{ scope.row.loginCount ?? 0 }}</el-text>
                        </el-row>
                        <el-row>
                            <el-text size="small" type="warning"
                                >失败次数:{{ scope.row.loginFailures ?? 0 }}
                            </el-text>
                        </el-row>
                    </template>
                    <template #options="scope">
                        <el-button-group>
                            <el-button
                                text
                                type="primary"
                                size="small"
                                @click="tableShow(scope.row)"
                                >查看
                            </el-button>
                            <el-button-group v-auths-all="['settingAdminEdit']">
                                <el-button
                                    text
                                    type="primary"
                                    size="small"
                                    @click="tableEdit(scope.row)"
                                    >{{ $t('编辑') }}
                                </el-button>
                                <el-popconfirm title="确定删除吗？" @confirm="tableDel(scope.row)">
                                    <template #reference>
                                        <el-button text type="primary" size="small"
                                            >{{ $t('删除') }}
                                        </el-button>
                                    </template>
                                </el-popconfirm>
                                <el-popconfirm
                                    title="确定注销吗？"
                                    @confirm="tableLogout(scope.row)"
                                >
                                    <template #reference>
                                        <el-button text type="danger" size="small"
                                            >{{ $t('强制注销') }}
                                        </el-button>
                                    </template>
                                </el-popconfirm>
                            </el-button-group>
                        </el-button-group>
                    </template>
                </kitegoTable>
            </el-main>
        </el-container>
    </el-container>

    <save-dialog
        v-if="state.dialog.save"
        ref="saveDialogRef"
        @success="handleSuccess"
        @closed="state.dialog.save = false"
    ></save-dialog>
</template>

<script setup lang="ts">
import saveDialog from './user-save.vue'
import { nextTick, onMounted, reactive, ref, watch } from 'vue'
import setting from '@/api/modules/setting.ts'
import type { ColumnProps, KitegoTableInstance } from '@/components/KitegoTable/type.ts'
import feedback from '@/utils/feedback.ts'
import { ElTree } from 'element-plus'
import type { FormModel } from '@/views/setting/user/type.ts'
import passport from '@/api/modules/passport.ts'

defineOptions({ name: '员工管理' })

// 表格配置项
const columns = reactive<ColumnProps[]>([
    { type: 'selection' },
    { prop: 'id', label: 'ID', width: 80, sortable: true },
    { prop: 'sort', label: '排序', width: 80, sortable: true },
    { prop: 'avatar', label: '头像', width: 80 },
    { prop: 'account', label: '登录账号', width: 100 },
    { prop: 'status', label: '账号状态', width: 100 },
    { prop: 'loginCount', label: '登录次数', width: 150 },
    { prop: 'nickname', label: '昵称', width: 100 },
    { prop: 'deptLabel', label: '部门', width: 100 },
    {
        prop: 'roleGroup',
        label: '所属角色',
        width: 200,
        filters: []
    },
    { prop: 'realName', label: '真实姓名', width: 150 },
    { prop: 'phone', label: '手机号', width: 150 },
    { prop: 'email', label: '邮箱', width: 150 },
    { prop: 'createTime', label: '加入时间', width: 180 },
    { prop: 'options', label: '操作', fixed: 'right', width: 280 }
])

interface SelectionModel {
    id: number
}

const selection = ref<SelectionModel[]>([])

const state = reactive({
    dialog: {
        save: false
    },
    groupFilterText: '',
    group: [],
    apiObj: setting.admin.list,
    search: {
        name: null
    },
    roleData: [{ id: '', label: '', value: '', text: '' }]
})

const kitegoTableRef = ref<KitegoTableInstance>()
const groupRef = ref<InstanceType<typeof ElTree>>()
const saveDialogRef = ref()

watch(
    () => state.groupFilterText,
    (val) => {
        groupRef.value!.filter(val)
    }
)

watch(
    () => state.roleData,
    (val) => {
        if (Array.isArray(val)) {
            val.forEach((item) => {
                item.value = item.id
                item.text = item.label
            })
        }

        const roleGroupColumn = columns.find((col) => col.prop === 'roleGroup')
        if (roleGroupColumn && roleGroupColumn.filters) roleGroupColumn.filters = state.roleData
    }
)

onMounted(() => {
    getGroup()
    getRole()
})

// 加载树数据
async function getRole() {
    const res = await setting.role.list.get({ page: 1, pageSize: 10000 })
    state.roleData = res.data
}

// 添加
function add() {
    state.dialog.save = true
    nextTick(() => {
        saveDialogRef.value?.open()
    })
}

// 删除
async function tableDel(row: FormModel) {
    row.deleteFlag = 1
    await edit(row)
}

// 注销
async function tableLogout(row: FormModel) {
    await passport.forceLogout.post({ userId: row.id })
}

// 编辑
function tableEdit(row: FormModel) {
    state.dialog.save = true
    nextTick(() => {
        saveDialogRef.value?.open('edit')
        saveDialogRef.value?.setData(row)
    })
}

// 查看
function tableShow(row: FormModel) {
    state.dialog.save = true
    nextTick(() => {
        saveDialogRef.value?.open('show')
        saveDialogRef.value?.setData(row)
    })
}

async function edit(row: FormModel) {
    const res = await setting.admin.edit.post(row)
    if (res) {
        feedback.success('操作成功')
        kitegoTableRef.value?.getTableList()
    }
}

// 批量删除
async function batchDel() {
    feedback
        .confirm(`确定删除选中的 ${selection.value.length} 项吗？`, '提示', {
            type: 'warning'
        })
        .then(async () => {
            feedback.loading()
            const reqData = {
                ids: selection.value.map((item) => item.id)
            }
            const res = await setting.admin.batchDel.post(reqData)
            if (res) {
                kitegoTableRef.value?.getTableList()
            }
            feedback.closeLoading()
        })
        .catch(() => {})
}

// 表格选择后回调事件
function selectionChange(value: SelectionModel[]) {
    selection.value = value
}

// 加载树数据
async function getGroup() {
    const data = await setting.dept.list.get()
    const allNode = { id: '', label: '所有' }
    data.unshift(allNode)
    state.group = data
}

// 树过滤
interface TreeModel {
    [key: string]: string
}

function groupFilterNode(value: string, data: TreeModel) {
    if (!value) return true
    return data.label.includes(value)
}

// 树点击事件
function groupClick(data: { id: number }) {
    kitegoTableRef.value!.searchParam = {
        groupId: data.id
    }
    kitegoTableRef.value?.search()
}

// 搜索
function handleSearch() {
    kitegoTableRef.value!.searchParam = state.search
    kitegoTableRef.value?.search()
}

// 本地更新数据
type Mode = 'add' | 'edit' | 'del'

function handleSuccess(data: FormModel, mode: Mode) {
    if (mode == 'add') {
        data.id = new Date().getTime()
        kitegoTableRef.value?.tableData.unshift(data)
    } else if (mode == 'edit') {
        kitegoTableRef.value?.tableData
            .filter((item) => item.id === data.id)
            .forEach((item) => {
                Object.assign(item, data)
            })
    }
    handleSearch()
}
</script>

<style scoped lang="scss"></style>
